package com.dunqi.gpm.shunqing.my;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.dunqi.gpm.shunqing.KongApp;
import com.dunqi.gpm.shunqing.MainActivity;
import com.dunqi.gpm.shunqing.R;
import com.dunqi.gpm.shunqing.WPConfig;
import com.dunqi.gpm.shunqing.common.api.ApiFactory;
import com.dunqi.gpm.shunqing.common.api.RxSchedulers;
import com.dunqi.gpm.shunqing.common.base.BaseAct;
import com.dunqi.gpm.shunqing.common.base.Data;
import com.dunqi.gpm.shunqing.common.base.Data3;
import com.dunqi.gpm.shunqing.common.util.CommonUtil;
import com.dunqi.gpm.shunqing.common.util.SPHelper;
import com.dunqi.gpm.shunqing.common.util.SharedPreferencesUtils;
import com.dunqi.gpm.shunqing.common.util.SignatureUtil;
import com.dunqi.gpm.shunqing.common.util.TimeUtil;
import com.dunqi.gpm.shunqing.common.util.UpgradeUtil;
import com.dunqi.gpm.shunqing.my.bean.User;
import com.dunqi.gpm.shunqing.my.util.JpushUtil;
import com.dunqi.gpm.shunqing.my.util.UserUtil;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.schedulers.ScheduledRunnable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class LoginActivity extends BaseAct {

    public static final String USER_TAGS = "user_tags";
    @BindView(R.id.username_edit)
    EditText usernameEdit;
    @BindView(R.id.password_edit)
    EditText passwordEdit;
    @BindView(R.id.vcode_edit)
    EditText vcodeEdit;
    @BindView(R.id.image_iv)
    ImageView imageIv;

    String[] permisions = {Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    int permisionCode = 400;

    @Override
    protected void refreshData(Bundle savedInstanceState) {
//        update();
    }

//    private void update() {
//        Disposable subscribe = UpgradeUtil.upgradeCheck(this);
//        addDisposables(subscribe);
//    }

    @Override
    protected void onPermissionSuccess(String[] permissions, int requestCode) {
        super.onPermissionSuccess(permissions, requestCode);
//        update();
        checkUpdate();
    }

    private void checkUpdate() {
        if (!WPConfig.isDebug)
            PgyUpdateManager.register(LoginActivity.this,
                    new UpdateManagerListener() {

                        @Override
                        public void onUpdateAvailable(final String result) {

                            // 将新版本信息封装到AppBean中
                            final AppBean appBean = getAppBeanFromString(result);
                            new android.app.AlertDialog.Builder(LoginActivity.this)
                                    .setTitle("新版本")
                                    .setMessage(appBean.getReleaseNote())
                                    .setNegativeButton(
                                            "更新",
                                            new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    startDownloadTask(LoginActivity.this, appBean.getDownloadURL());
                                                }
                                            }).show();
                        }

                        @Override
                        public void onNoUpdateAvailable() {
                        }
                    });
    }

    @Override
    protected void onPermissionFailed(int requestCode) {
        super.onPermissionFailed(requestCode);

    }

    @Override
    protected void initUiAndListener() {
        test();
        boolean stopped = JPushInterface.isPushStopped(this);
        if (stopped) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("APP注册到消息推送服务器失败，不允许登录，请检查你的手机网络或联系管理员");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.show();
        } else {
            String appToken = UserUtil.getAppToken();
            User user = UserUtil.getUser();
            if (user != null && !TextUtils.isEmpty(appToken) &&
                    TimeUtil.convertToUnix(user.getTokenExpireDate()) > System.currentTimeMillis()) {
                Set sets = SharedPreferencesUtils.getSetData(USER_TAGS);
                Set set = JpushUtil.setTags(sets);
                checkTagAndStart(set);
                return;
            }
        }
        imageIv.performClick();
        //可有可无吧，之前有问题，后来突然消失，这里稳一波
        setBackground(R.color.color_005fff);

        if (SPHelper.init(LoginActivity.this).getBoolean("remember")) {
            SPHelper.init(LoginActivity.this).put("remember", true);
            String username = SPHelper.init(LoginActivity.this).getString("username");
            String password = SPHelper.init(LoginActivity.this).getString("password");
            usernameEdit.setText(username);
            passwordEdit.setText(password);
        } else if ("no".equals(SPHelper.init(LoginActivity.this).getString("fisrt"))) {
            CheckBox viewById = findViewById(R.id.config_remember);
            viewById.setChecked(false);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            checkUpdate();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.image_iv, R.id.config_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_iv:
//                getVcode();
                break;
            case R.id.config_btn:
                login();
                break;
            default:
                break;
        }
    }

    @Override
    public View getStateView() {
        return null;
    }

    @SuppressLint("CheckResult")
    private void login() {
        final String username = usernameEdit.getText().toString().trim();
        final String password = passwordEdit.getText().toString().trim();
        String vcode = "kong";//专属标记，网名

        String digestPassword = SignatureUtil.digest(password, null).toLowerCase();

        final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在登录...");

        ApiFactory.getInstance()
                .login(username, digestPassword, vcode, CommonUtil.getDeviceId())
                .compose(RxSchedulers.<Data<User>>io_main())
                .subscribe(new Consumer<Data<User>>() {
                    @Override
                    public void accept(Data<User> data) throws Exception {
                        int resultCode = data.getResultCode();
                        if (resultCode == 1) {

                            User user = data.getData();


                            List<Data3> data3 = data.getData3();
                            if (data3 != null || !data3.isEmpty()) {
                                for (Data3 data31 : data3) {
                                    user.getUserRoles().put(data31.getRoleCode(), data31);
                                }
                                user.setBaseUrl(data.getData2());
                            }
                            UserUtil.saveUser(user);

                            Set<String> strings = JpushUtil.setTags(data3);
                            CheckBox viewById = findViewById(R.id.config_remember);
                            SPHelper.init(LoginActivity.this).put("fisrt", "no");
                            if (viewById.isChecked()) {
                                SPHelper.init(LoginActivity.this).put("remember", true);
                                SPHelper.init(LoginActivity.this).put("username", username);
                                SPHelper.init(LoginActivity.this).put("password", password);
                            } else {
                                SPHelper.init(LoginActivity.this).put("remember", false);
                                SPHelper.init(LoginActivity.this).put("username", "");
                                SPHelper.init(LoginActivity.this).put("password", "");
                            }
                            checkTagAndStart(strings);
                            return;
                        }
                        String resultMessage = data.getResultMessage();
                        if (!TextUtils.isEmpty(resultMessage)) {
                            vcodeEdit.setText("");
                            CommonUtil.showSingleToast(resultMessage);
                        }
                        imageIv.performClick();
                        dialog.dismiss();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        t("登录失败");
                        dialog.dismiss();
                        imageIv.performClick();
                        vcodeEdit.setText("");
                    }
                });
    }

    /**
     * 检查后台tag是否有效，含有无效的就提示用户
     *
     * @param strings
     */
    private void checkTagAndStart(Set<String> strings) {
        if (strings.isEmpty()) {
            KongApp.finishAllActivity();
            startActivity(new Intent(getActivity(), MainActivity.class));
        } else {
            StringBuilder sb = new StringBuilder("设置用户推送tag:");
            for (String string : strings) {
                sb.append(string);
            }
            sb.append("失败，请联系管理员");
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(sb);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.show();
        }
    }

    private void getVcode() {
        ApiFactory.getInstance()
                .getVcode(System.currentTimeMillis())
                .compose(RxSchedulers.<ResponseBody>io_main())
                .subscribe(new Consumer<ResponseBody>() {
                    @Override
                    public void accept(ResponseBody responseBody) {
                        Bitmap bitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                        imageIv.setImageBitmap(bitmap);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {

                    }
                });

        ApiFactory.getInstance()
                .getVcode(System.currentTimeMillis()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<ResponseBody>() {
            @Override
            public void accept(ResponseBody responseBody) {
                Bitmap bitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                imageIv.setImageBitmap(bitmap);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
            }
        });

        ApiFactory.getInstance()
                .getVcode(System.currentTimeMillis()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ResponseBody value) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void test() {
        ApiFactory.getInstance()
                .postUrl("http://192.168.1.8:8080/gpm-web-opration/project/test.do")
                .compose(RxSchedulers.<String>io_main())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String value) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}